package info.webest.reminder.contacts;

import info.webest.menulist.wbMenuListAdapter;
import info.webest.menulist.wbMenuListItem;
import info.webest.reminder.Options;
import info.webest.reminder.R;

import java.util.ArrayList;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Groups;
import android.provider.ContactsContract.Settings;
import android.widget.ListView;

public class ContactAccounts {

	public static ContactActivity activity = null;

	private static ArrayList<ContactAccount> contactAccounts = null;
	private static Drawable icon = null;
	private static int iconId = 0;

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
	public static void getContactAccount(final ContactActivity activity,
			final ListView lvContacts) {

		// ContactAccounts.context = context;

		// ACCOUNT LIST
		ArrayList<Account> accounts = new ArrayList<Account>();
		ArrayList<wbMenuListItem> menu = new ArrayList<wbMenuListItem>();

		contactAccounts = new ArrayList<ContactAccount>();

		Uri uri = ContactsContract.Data.CONTENT_URI;
		// ContactsContract.RawContacts.CONTENT_URI;
		// ContactsContract.Data.CONTENT_URI;
		// ContactsContract.RawContacts.CONTENT_URI;

		String[] projection = new String[] {
				// ContactsContract.CommonDataKinds.Event.CONTACT_ID,
				ContactsContract.RawContacts.ACCOUNT_NAME,
				ContactsContract.RawContacts.ACCOUNT_TYPE };

		String where = ContactsContract.CommonDataKinds.Event.CONTACT_ID
				+ " = " + ContactsContract.RawContacts.CONTACT_ID + " AND "
				+ ContactsContract.Data.MIMETYPE + "= ?";
		String[] selectionArgs = new String[] { ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };

		String sortOrder = ContactsContract.RawContacts.ACCOUNT_TYPE + ", "
				+ ContactsContract.RawContacts.ACCOUNT_NAME;
		// ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"

		ContentResolver cr = activity.getContentResolver();

		Cursor cursor = cr.query(uri, projection, where, selectionArgs,
				sortOrder);

		Account a = null;
		int i = 0;

		while (cursor.moveToNext()) {

			if (cursor.getString(0) != null && cursor.getString(1) != null) {

				a = new Account(cursor.getString(0), cursor.getString(1));
				i = accounts.indexOf(a);

				if (i < 0) {

					accounts.add(a);
					contactAccounts.add(new ContactAccount(cursor.getString(0),
							cursor.getString(1)));
				} else {
					contactAccounts.get(i).count++;
				}
			}
		}

		String type = null;
		String packageName = null;

		// if (accounts.size() > 1) {

		for (ContactAccount account : contactAccounts) {

			icon = null;
			iconId = 0;

			if (account.type.equals("com.google")) {
				type = "Google";
				packageName = "com.google.android.gm";
			} else if (account.type.equals("com.skype.contacts.sync")) {
				type = "Skype";
				packageName = "com.skype.raider";
			} else if (account.type.equals("com.vkontakte.account")) {
				type = "VKontakte";
				packageName = "com.vkontakte.android";
			} else if (account.type.equals("com.viber.voip.account")) {
				type = "Viber";
				packageName = "com.viber.voip";
			} else if (account.type.equals("com.icq.mobile.client")) {
				type = "ICQ";
				packageName = "com.icq.mobile.client";
			} else if (account.type.startsWith("SIM ")) {
				type = account.type;
				packageName = null;
				iconId = R.drawable.ic_sim_card;
			} else {
				type = account.type;
				packageName = null;
			}

			try {
				if (packageName != null) {
					icon = activity.getPackageManager().getApplicationIcon(
							packageName);
				}
			} catch (PackageManager.NameNotFoundException e) {
				icon = null;
			}

			menu.add(new wbMenuListItem(activity,//
					iconId, // resource Id of icon
					icon, // action icon //R.drawable.ic_launcher
					type + " (" + account.count + ")", // action name
					account.name) // action description
			);
		}

		final wbMenuListAdapter adapter = new wbMenuListAdapter(activity,
				R.layout.menu_list_row, menu);

		AlertDialog dialog;
		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
		builder.setTitle(R.string.account_list);
		// builder.setCancelable(false);

		builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
			@Override
			public void onCancel(DialogInterface arg0) {
				activity.finish();
			}
		});

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
			builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
				@Override
				public void onDismiss(DialogInterface dialog) {
					// context.finish();
				}
			});
		}

		builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialogInterface, int id) {

				String accountName = adapter.getItem(id).comment.toString();
				String accountType = contactAccounts.get(id).type;

				SharedPreferences prefs = PreferenceManager
						.getDefaultSharedPreferences(activity
								.getApplicationContext());

				SharedPreferences.Editor editor = prefs.edit();
				editor.putString(Options.ACCOUNT_NAME, accountName);
				editor.putString(Options.ACCOUNT_TYPE, accountType);
				editor.commit();

				// ////////////////////////////////////////
				ContactActivity.AccountName = accountName;
				ContactActivity.AccountType = accountType;
				// ////////////////////////////////////////
				activity.showData();
				// ////////////////////////////////////////

				ContactActivity.WidgetRefresh(activity);
			}
		});

		dialog = builder.create();
		dialog.show();
		// }

		// return accountName;
	}

	@SuppressWarnings("unused")
	private Account[] getAccountArray(Context context) {

		String type = null;
		// Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
		Account[] accounts = AccountManager.get(context).getAccounts();

		if (accounts.length > 1) {

			for (Account account : accounts) {
				// if (emailPattern.matcher(account.name).matches()) {
				// String possibleEmail = account.name;
				// }

				type = "Unknown";

				if (account.type.equals("com.google")) {
					type = "Google";
				} else if (account.type.equals("com.android.email")) {
					type = "Email";
				} else if (account.type.equals("com.dropbox.android.account")) {
					type = "Dropbox";
				} else if (account.type.equals("com.skype.contacts.sync")) {
					type = "Skype";
				} else if (account.type.equals("com.viber.voip.account")) {
					type = "Viber";
				} else if (account.type.equals("com.icq.mobile.client")) {
					type = "ICQ";
				} else if (account.type.equals("com.shazam.android")) {
					type = "Shazam";
				} else
					type = account.type;
			}
		}
		return accounts;

	}

	public void createAccaunt(Context context, String accauntName,
			String accountType) {
		// http://stackoverflow.com/questions/4361005/account-doesnt-appear-in-contacts-app-settings-on-device-from-htc/4361329#4361329
		// http://stackoverflow.com/questions/5825577/android-enable-imported-account-contacts-programmatically/6545592#6545592
		ContentProviderClient client = context.getContentResolver()
				.acquireContentProviderClient(ContactsContract.AUTHORITY_URI);

		ContentValues values = new ContentValues();
		values.put(ContactsContract.Groups.ACCOUNT_NAME, accauntName);
		values.put(Groups.ACCOUNT_TYPE, accountType);
		// values.put(Settings.UNGROUPED_VISIBLE, true);

		try {
			client.insert(
					Settings.CONTENT_URI
							.buildUpon()
							.appendQueryParameter(
									ContactsContract.CALLER_IS_SYNCADAPTER,
									"true").build(), values);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

}
